/**
@Description  请填写文件描述（需要改）
@author: freedom
@date: 2021/5/25
@note:
**/
package es

import (
	"context"
	"encoding/json"
	"gin-vue-admin/global"
	"gin-vue-admin/model"
	"gin-vue-admin/model/request"
	"github.com/olivere/elastic/v7"
)

// es插入数据
func AddDocument(index string, document interface{}) (string, error) {
	res, err := global.GVA_ES.Index().Index(index).BodyJson(document).Do(context.Background())
	if err != nil {
		global.GVA_LOG.Error("add document failed," + err.Error())
	}
	id := res.Id
	return id, err
}

// es删除数据
func DeleteDocument(index string, id string) error {
	_, err := global.GVA_ES.Delete().Index(index).Index(id).Do(context.Background())
	if err != nil {
		global.GVA_LOG.Error("delete a document failed," + err.Error())
	}
	return err
}

// es更新数据
func UpdateDocument(index string, id string, documentMap map[string]interface{}) error {
	_, err := global.GVA_ES.Update().Index(index).Id(id).Doc(documentMap).Do(context.Background())
	if err != nil {
		global.GVA_LOG.Error("update a document failed," + err.Error())
	}
	return err
}

// es根据ID查询数据
func QueryDocumentById(index string, id string) (*elastic.GetResult, error) {
	document, err := global.GVA_ES.Get().Index(index).Id(id).Do(context.Background())
	if err != nil {
		global.GVA_LOG.Error("query a document by id failed," + err.Error())
	}
	return document, err
}

// 根据文章标题查询
func QueryDocumentByTitle(index string, title string) (string, error) {
	document, err := global.GVA_ES.Search().Index(index).Query(elastic.NewTermQuery("title.keyword", title)).Do(context.Background())
	if err != nil {
		global.GVA_LOG.Error("query a document by title failed," + err.Error())
		return "", err
	}
	if document.Hits.TotalHits.Value >= 1 {
		return "id", err
	} else {
		return "", err
	}
}

// 根据查询条件分页查询
func QueryDocumentBySearchInfo(index string, info request.SysKnowledgeSearch) (sysknowledges interface{}, total int64, err error) {
	var from = (info.Page - 1) * info.PageSize
	query := elastic.NewBoolQuery()
	// 标签搜索
	if len(info.Tags) > 0 {
		for _, value := range info.Tags {
			query = query.Must(elastic.NewConstantScoreQuery(elastic.NewMatchQuery("tags", value)))

		}
	}
	// 标题和内容模糊匹配
	if info.Title != "" {
		titleQuery := elastic.NewMatchQuery("title", info.Title)
		contentQuery := elastic.NewMatchQuery("content", info.Title)
		query.Should(titleQuery, contentQuery).MinimumNumberShouldMatch(1)
	}
	// 高亮显示
	highlight := elastic.NewHighlight().Field("title").Field("content")
	highlight = highlight.PreTags("<span style=\"color:blue;\">").PostTags("</span>")

	document, err := global.GVA_ES.Search().Highlight(highlight).Query(query).Index(index).Sort("update_time", false).From(from).Size(info.PageSize).Do(context.Background())
	if err != nil {
		global.GVA_LOG.Error("query documents by search failed," + err.Error())
		return nil, 0, err
	}
	// 对象映射
	var sysKnowledges []model.SysKnowledge
	num := document.Hits.TotalHits.Value
	if num >= 1 {
		for _, hits := range document.Hits.Hits {
			sysKnowledge := model.SysKnowledge{}
			err := json.Unmarshal([]byte(hits.Source), &sysKnowledge)
			if err != nil {
				global.GVA_LOG.Error("unmarshal json to sysKnowledge failed," + err.Error())
			}
			// 设置高亮
			sysKnowledge.Highlight = hits.Highlight
			sysKnowledge.Id = hits.Id
			sysKnowledges = append(sysKnowledges, sysKnowledge)
		}
	} else {
		return nil, 0, err
	}
	return sysKnowledges, num, err
}

// 联想词搜索

func QuerySuggestByTitle(index string, info model.SysKnowledge) ([]string, error) {
	documents, err := global.GVA_ES.Search().Index(index).Suggester(elastic.NewCompletionSuggester("my-suggest").Prefix(info.Title).Field("title.suggest")).Do(context.Background())
	if err != nil {
		global.GVA_LOG.Error("query a suggest by title failed," + err.Error())
		return nil, err
	}

	var strs []string
	if len(documents.Suggest["my-suggest"][0].Options) > 0 {
		for _, str := range documents.Suggest["my-suggest"][0].Options {
			strs = append(strs, str.Text)
		}

	}
	return strs, err
}
